package com.example.demo.service.impl;

import com.example.demo.entity.Category;
import com.example.demo.exception.BusinessException;
import com.example.demo.exception.ErrorCode;
import com.example.demo.mapper.CategoryMapper;
import com.example.demo.service.CategoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl implements CategoryService {
    private static final Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Category createCategory(String name, Integer status, Integer order) {
        logger.info("Creating new category with name: {}, status: {}, order: {}", name, status, order);
        
        // Check if category already exists
        List<Category> categories = categoryMapper.getCategoryList(name, null);
        if (!categories.isEmpty()) {
            logger.warn("Category already exists with name: {}", name);
            throw new BusinessException(ErrorCode.CATEGORY_ALREADY_EXISTS);
        }

        Category category = new Category();
        category.setName(name);
        category.setStatus(status);
        category.setOrder(order);
        category.setCreate_time(new Date());
        category.setUpdate_time(new Date());
        
        categoryMapper.insert(category);
        logger.info("Successfully created category with id: {}", category.getId());
        return category;
    }

    @Override
    public boolean updateCategory(Integer id, String name, Integer status, Integer order) {
        logger.info("Updating category id: {} with new name: {}, status: {}, order: {}", id, name, status, order);
        
        Category category = getCategoryById(id);
        category.setName(name);
        if (status != null) {
            category.setStatus(status);
        }
        if (order != null) {
            category.setOrder(order);
        }
        category.setUpdate_time(new Date());
        
        int result = categoryMapper.update(category);
        if (result == 0) {
            logger.error("Failed to update category id: {}", id);
            throw new BusinessException(ErrorCode.CATEGORY_NOT_FOUND);
        }
        
        logger.info("Successfully updated category id: {}", id);
        return true;
    }

    @Override
    public boolean updateCategoryStatus(Integer id, Integer status) {
        logger.info("Updating status for category id: {} to status: {}", id, status);
        
        int result = categoryMapper.updateStatus(id, status);
        if (result == 0) {
            logger.error("Failed to update status for category id: {}", id);
            throw new BusinessException(ErrorCode.CATEGORY_NOT_FOUND);
        }
        
        logger.info("Successfully updated status for category id: {}", id);
        return true;
    }

    @Override
    public boolean deleteCategory(Integer id) {
        logger.info("Deleting category id: {}", id);
        
        int result = categoryMapper.deleteById(id);
        if (result == 0) {
            logger.error("Failed to delete category id: {}", id);
            throw new BusinessException(ErrorCode.CATEGORY_NOT_FOUND);
        }
        
        logger.info("Successfully deleted category id: {}", id);
        return true;
    }

    @Override
    public Category getCategoryById(Integer id) {
        logger.debug("Getting category by id: {}", id);
        
        Category category = categoryMapper.getCategoryById(id);
        if (category == null) {
            logger.error("Category not found with id: {}", id);
            throw new BusinessException(ErrorCode.CATEGORY_NOT_FOUND);
        }
        
        return category;
    }

    @Override
    public Map<String, Object> getCategoryList(Integer page, Integer limit, String keyword, String orderBy) {
        logger.info("Getting category list - page: {}, limit: {}, keyword: {}, orderBy: {}", page, limit, keyword, orderBy);
        PageHelper.startPage(page, limit);
        List<Category> categories = categoryMapper.getCategoryList(keyword, orderBy);
        PageInfo<Category> pageInfo = new PageInfo<>(categories);

        // Build result map
        Map<String, Object> result = new HashMap<>();
        result.put("list", categories);
        result.put("totalCount", pageInfo.getTotal());
        
        logger.info("Fetched {} coupons on page {}", categories.size(), page);
        return result;
    }
}
